from flow_alchemy.collects import flows
from flow_alchemy.db import session
from flow_alchemy.db.models import WorkFlow, Node, Edge


def update_flow(fid):
    ctrl = flows.get(fid, None)
    if not ctrl:
        raise Exception('{fid} does not exist ')
    data = []
    flow = WorkFlow(
        fid=fid,
        name=ctrl.name,
        category=ctrl.category,
        work_tables=ctrl.model.__name__,
        doc=ctrl.doc
    )
    data.append(flow)
    for nid, node in ctrl.items():
        node_model = Node(fid=fid, nid=nid, name=node.name,
                          has_user=node.has_user,
                          has_role=node.has_role,
                          doc=node.doc,
                          node_type=node.node_type)
        if node_model.node_type == 'StartNode':
            node_model.has_submit = True
            node_model.has_save = True
            node_model.has_void = True

        elif node_model.node_type == 'RoleNode' or node_model.node_type == 'UserNode':
            node_model.has_pass = True
            node_model.has_reject = True

        data.append(node_model)

        for child, fun, name in node.child:
            edge = Edge(parent_id=node.nid, child_id=child.nid, fid=fid,
                        name=name, doc=fun.__doc__, create_uid=1)
            data.append(edge)

    print('清空')
    session.execute(f"delete FROM {WorkFlow.__tablename__} where fid= {fid}")
    session.execute(f"delete FROM {Node.__tablename__} where fid= {fid}")
    session.execute(f"delete FROM {Edge.__tablename__} where fid= {fid}")
    # session.execute(f"delete table {NodeConfig.__tablename__} where fid= {fid}")
    print('清空完成')

    session.add_all(data)
    session.commit()


if __name__ == '__main__':
    print(__name__)
    update_flow(1000)
